<?php


namespace app\wechat\controller;

use app\common\model\AppointmentOrder;
use app\common\model\Order;
use app\wechat\model\OfflineOrderModel;
use think\Controller;

use EasyWeChat\Factory;
use think\Db;


class Pay extends Controller
{
    public function notify()
    {

        $options = config("wechat_easy");

        $options = [
            'app_id' => 'wx41e3fa46bbc8f0ad',
            'secret' => '6b560fbd6101cb09455372e393a59686',
            'token' => '',
            'response_type' => 'array',
            //...
        ];

        $app =  Factory::officialAccount($options);

        $body = [
            'body' => '会查查-参赛报名费',
            'out_trade_no' =>123456789456,
            'total_fee' => 5 * 100,
            //'spbill_create_ip' => get_client_ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            // 'notify_url' => 'https://www.huixx.cn/index/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => 'obBHk01ciT8CVi--c1_frKdL_V0U',
            //'sandbox' => true, // 设置为 false 或注释则关闭沙箱模式
        ];

        //$app->jssdk->buildConfig( $body, $debug = false, $beta = false, $json = false, $openTagList = []);

//        $app->jssdk->setUrl();

        return $this->fetch('notify',compact('app'));
    }

    /*
     * 师傅端请求按钮
     */
    public function serverButton()
    {
        $order_id = input('order_id');

        if(empty($order_id)){
            return json(['code'=>0,'msg'=>'缺少order_id2']);
        }

        $order_model = Db::name('appointment_order')
            ->alias('app')
            ->join('order','app.user_order_id = order.order_id','left')
            ->field('app.*,order.total_price')
            ->where(['app.id'=>$order_id,'app.is_offline'=>1])
            ->find();

        if(!$order_model){
            return json(['code'=>0,'msg'=>'当前订单不存在']);
        }

        if($order_model['offline_pay_status'] == 1){
            return json(['code'=>0,'msg'=>'订单已支付，请勿重复支付']);
        }

        if($order_model['total_price'] == 0){
//            var_dump($order_model);
            $appointmentModel = AppointmentOrder::get(['id'=>$order_model['id']]);
            $Order = new AppointmentOrder();
//            var_dump($appointmentModel);die;

            $orderModel = Order::get(['order_id'=>$appointmentModel['user_order_id']]);
            $res = [];
            Db::startTrans();
            $appointmentModel->offline_pay_status = 1;
//                $appointmentModel->status = 2;
            $Order->updateServerState($order_model['id'], 4);
            $res[] = $appointmentModel->save();
            $orderModel->pay_status = 20;
            $orderModel->pay_type = 20;
            $orderModel->pay_time = time();
            $orderModel->pay_price = 0;
            $res[] = $orderModel->save();

            if(check_arr($res) == false){
                Db::rollback();
                log_print($res);
                log_print('订单操作失败');
            }else{
                Db::commit();
                log_print('订单操作成功');
            }

            return json(['code'=>1,'msg'=>'确认支付成功']);

        }else{

            return json(['code'=>0,'msg'=>'需扫码确认']);

        }
    }

    public function index()
    {
        $wechat_config = config("wechat_easy");

        $order_id = input('order_id');
        if(empty($order_id)){
            return json(['code'=>0,'msg'=>'缺少order_id2']);
        }

        $wechat = Factory::officialAccount($wechat_config);
        $oauth = $wechat->oauth;
        $wxuser = session('wechat_user');

        // 未登录
        if (empty($wxuser)) {
            session('order_id_callback', $order_id);
            session('target_url_index', $_SERVER['PATH_INFO']);
            return $oauth->redirect()->send();
            exit;
        }


        $order_model = Db::name('appointment_order')
                        ->alias('app')
                        ->join('order','app.user_order_id = order.order_id','left')
                        ->field('app.*,order.total_price')
                        ->where(['app.id'=>$order_id,'app.is_offline'=>1])
                        ->find();

        if(!$order_model){
            return json(['code'=>0,'msg'=>'当前订单不存在']);
        }

        if($order_model['offline_pay_status'] == 1){
            return json(['code'=>0,'msg'=>'订单已支付，请勿重复支付']);
        }

        if($order_model['total_price'] == 0){
//            var_dump($order_model);
            $appointmentModel = AppointmentOrder::get(['id'=>$order_model['id']]);
            $Order = new AppointmentOrder();
//            var_dump($appointmentModel);die;

            $orderModel = Order::get(['order_id'=>$appointmentModel['user_order_id']]);
            $res = [];
            Db::startTrans();
            $appointmentModel->offline_pay_status = 1;
//                $appointmentModel->status = 2;
            $Order->updateServerState($order_model['id'], 4);
            $res[] = $appointmentModel->save();
            $orderModel->pay_status = 20;
            $orderModel->pay_type = 20;
            $orderModel->pay_time = time();
            $orderModel->pay_price = 0;
            $res[] = $orderModel->save();

            if(check_arr($res) == false){
                Db::rollback();
                log_print($res);
                log_print('订单操作失败');
            }else{
                Db::commit();
                log_print('订单操作成功');
            }

            return $this->fetch('success');
            die;
        }



        //var_dump($wechat_config['payment']['default']);
        $app = Factory::payment($wechat_config['payment']['default']);

        $offlineModel = new OfflineOrderModel;

        $out_trade_no = '2020'.time().$order_id;
        $result = $app->order->unify([
            'body' => $order_model['offline_name'],
            'out_trade_no' => $out_trade_no,
            'total_fee' => intval($order_model['total_price'] * 100),
            //'total_fee' => 1,
            //'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' =>$wxuser['id'],
        ]);

        $data = [
            'order_no'=>$out_trade_no,
            'order_id'=>$order_id,
            'total_fee'=>intval($order_model['total_price']),
        ];

        $offlineModel->save($data);

        $jssdk = $app->jssdk;


        $config  = $jssdk->sdkConfig($result['prepay_id']);

        return $this->fetch('index',compact('config'));
    }


    public function callback()
    {
        $order_id = session('order_id_callback');
        session('order_id_callback', 0);
        if(empty($order_id)){
            return json(['code'=>0,'msg'=>'缺少order_id1']);
        }

        $app = Factory::officialAccount(config("wechat_easy"));
        $oauth = $app->oauth;

        $user = $oauth->user();

        session('wechat_user', $user->toArray());

        $this->redirect(session('target_url_index').'?order_id='.$order_id);
         // 跳转到 user/profile

    }


    public function order_notify()
    {
        //处理微信支付回调
        $testxml  = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);//转成数组，
        if($result){

            log_print($result);
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                $model = OfflineOrderModel::get(['order_no'=>$result['out_trade_no']]);
                if(!$model){
                    log_print('线下订单记录未找到');
                    return 'SUCCESS';
                }

                if ($model['status'] == 1){
                    log_print('订单状态已支付');
                    return 'SUCCESS';
                }

                $appointmentModel = AppointmentOrder::get(['id'=>$model['order_id']]);

                if(!$appointmentModel){
                    log_print('预约订单未找到');
                    return 'SUCCESS';

                }
                $orderModel = Order::get(['order_id'=>$appointmentModel['user_order_id']]);
                $Order = new AppointmentOrder();
                if(!$appointmentModel){
                    log_print('预约订单未找到');
                    return 'SUCCESS';
                }
                $res = [];
                Db::startTrans();
                $appointmentModel->offline_pay_status = 1;
//                $appointmentModel->status = 2;
                $Order->updateServerState($model['order_id'], 4);
                $res[] = $appointmentModel->save();
                $orderModel->pay_status = 20;
                $orderModel->pay_type = 20;
                $orderModel->pay_time = time();
                $orderModel->pay_price = $result['total_fee'] * 100;
                $res[] = $orderModel->save();
                $model->status = 1;
                $res[] = $model->save();

                if(check_arr($res) == false){
                    Db::rollback();
                    log_print($res);
                    log_print('订单操作失败');
                }else{
                    Db::commit();
                    log_print('订单操作成功');
                }
            }

            return 'SUCCESS';

        }

    }

}